package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nineclock.common.entity.PageResult;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.dto.SysRoleDTO;
import com.nineclock.system.excel.ExcelMember;
import com.nineclock.system.excel.MemberParseListener;
import com.nineclock.system.mapper.*;
import com.nineclock.system.pojo.*;
import com.nineclock.system.service.SysCompanyUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
@Slf4j
@Transactional
public class SysCompanyUserServiceImpl implements SysCompanyUserService {

    @Autowired
    SysCompanyUserMapper companyUserMapper;

    @Override
    public List<SysCompanyUserDTO> queryCompanyMemberList() {
        //获取企业id
        Long companyId = CurrentUserHolder.get().getCompanyId();

        //配置条件
        LambdaQueryWrapper<SysCompanyUser>  wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUser::getCompanyId, companyId);
        wrapper.eq(SysCompanyUser::getEnable, 1); //员工 是否有效（可用）
        //查询员工列表
        List<SysCompanyUser> companyUserList = companyUserMapper.selectList(wrapper);

        if(CollectionUtil.isNotEmpty(companyUserList)){
            return BeanHelper.copyWithCollection(companyUserList, SysCompanyUserDTO.class);
        }

        return null;
    }

    @Autowired
    SysDepartmentMapper departmentMapper;

    @Override
    public PageResult<SysCompanyUserDTO> queryMembers(Integer page, Integer pageSize, String keyword, Long departmentId) {
        //健壮性判断
        if(page == null || pageSize == null ){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        // 存储部门及 子部门id
        List<Long> ids = new ArrayList<>();
        //添加部门id
        if(departmentId != 0){
            ids.add(departmentId);
        }
        //添加 子部门id
        this.queryChildDepartmentIds(ids, departmentId);


        //创建分页条件参数
        Page<SysCompanyUser> companyUserPage = new Page(page, pageSize);
        //创建wrapper条件
        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.in(SysCompanyUser::getDepartmentId, ids);

        if(StrUtil.isNotEmpty(keyword)){
            wrapper.and(wrapper1 -> {
                wrapper1.like(SysCompanyUser::getMobile, keyword)
                        .or().like(SysCompanyUser::getUserName, keyword)
                        .or().like(SysCompanyUser::getWorkNumber, keyword);
            });
        }
        //分页查询
        companyUserPage = companyUserMapper.selectPage(companyUserPage, wrapper);

        //要在页面展示的记录
        List<SysCompanyUser> records = companyUserPage.getRecords();
        if(CollectionUtil.isNotEmpty(records)){
            List<SysCompanyUserDTO> companyUserDTOList = BeanHelper.copyWithCollection(records, SysCompanyUserDTO.class);
            PageResult<SysCompanyUserDTO> pageResult = new PageResult<>(companyUserPage.getTotal(), companyUserPage.getPages(), companyUserDTOList);
            return pageResult;
        }


        return new PageResult<>();
    }

    @Override
    public void importMembers(MultipartFile excelFile) throws IOException {
        if(excelFile == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //执行读操作
        EasyExcel.read(
                excelFile.getInputStream(),
                ExcelMember.class,
                new MemberParseListener(this)).sheet(0).doRead();
    }
    @Autowired
    SysUserMapper userMapper;

    @Autowired
    SysRoleMapper roleMapper;

    @Autowired
    SysCompanyUserRoleMapper companyUserRoleMapper;

    @Override
    public void saveData(List<ExcelMember> list) {
        for (ExcelMember excelMember : list) {
            //健壮性判断
            //判断 手机号， 邮箱 是否重复， 判断工号是否重复
            LambdaQueryWrapper<SysUser> userQw = new LambdaQueryWrapper<>();
            userQw.eq(SysUser::getMobile, excelMember.getMobile())
                    .or().eq(SysUser::getEmail, excelMember.getEmail());
            Integer count = userMapper.selectCount(userQw);
            if(count > 0){
                throw new NcException(ResponseEnum.USER_MOBILE_EMAIL_EXISTS);
            }

            LambdaQueryWrapper<SysCompanyUser> companyUserQw = new LambdaQueryWrapper<>();
            companyUserQw.eq(SysCompanyUser::getWorkNumber, excelMember.getWorkNumber());

            Integer count1 = companyUserMapper.selectCount(companyUserQw);
            if(count1 > 0){
                throw new NcException(ResponseEnum.WROK_NUM_EXISTS);
            }


            //新增用户信息
            SysUser user = new SysUser();
            user.setUsername(excelMember.getName());
            user.setMobile(excelMember.getMobile());
            user.setEmail(excelMember.getEmail());
            user.setStatus((short)1);
            user.setCreateTime(new Date());
            user.setPassword(new BCryptPasswordEncoder().encode("123456")); //初始密码
            user.setLastLoginCompanyId(CurrentUserHolder.get().getCompanyId());

            userMapper.insert(user);

            //员工
            SysCompanyUser companyUser = new SysCompanyUser();
            companyUser.setUserName(excelMember.getName());
            companyUser.setUserId(user.getId());
            companyUser.setCompanyId(CurrentUserHolder.get().getCompanyId());
            companyUser.setCompanyName(CurrentUserHolder.get().getCompanyName());
            companyUser.setEnable((short)1);
            companyUser.setCreateTime(new Date());
            companyUser.setMobile(excelMember.getMobile());
            companyUser.setEmail(excelMember.getEmail());
            companyUser.setWorkNumber(excelMember.getWorkNumber());
            companyUser.setOfficeAddress(excelMember.getWorkAddr());
            companyUser.setTimeEntry(excelMember.getEntryTime());
            companyUser.setPost(excelMember.getPosition());
            companyUser.setRemark(excelMember.getDesc());

            //设置部门信息
            //根据部门名称查询部门对象
            LambdaQueryWrapper<SysDepartment> departmentQw = new LambdaQueryWrapper<>();
            departmentQw.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
            departmentQw.eq(SysDepartment::getName, excelMember.getDepartmentName());
            SysDepartment department = departmentMapper.selectOne(departmentQw);
            if(department != null){
                companyUser.setDepartmentId(department.getId());
                companyUser.setDepartmentName(department.getName());
            }

            companyUserMapper.insert(companyUser);

            //根据角色名称 查询角色对象
            LambdaQueryWrapper<SysRole> roleQw = new LambdaQueryWrapper<>();
            roleQw.eq(SysRole::getCompanyId, CurrentUserHolder.get().getCompanyId());
            roleQw.eq(SysRole::getRoleDesc, excelMember.getRoleName());
            SysRole role = roleMapper.selectOne(roleQw);

            if(role != null){
                //员工和角色的关系
                SysCompanyUserRole companyUserRole = new SysCompanyUserRole();
                companyUserRole.setRoleId(role.getId());
                companyUserRole.setCompanyUserId(companyUser.getId());
                companyUserRole.setCompanyId(CurrentUserHolder.get().getCompanyId());

                companyUserRoleMapper.insert(companyUserRole);
            }


        }
    }

    @Override
    public SysCompanyUserDTO queryOne(String mobile) {
        if(mobile == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.eq(SysCompanyUser::getMobile, mobile);
        SysCompanyUser companyUser = companyUserMapper.selectOne(wrapper);
        if(companyUser != null){
            return  BeanHelper.copyProperties(companyUser, SysCompanyUserDTO.class);
        }
        return null;
    }

    @Override
    public Integer queryUserCountByDepartmentIds(List<Long> departmentIds) {
        if(CollectionUtil.isEmpty(departmentIds)){
            return 0;
        }
        //存储 部门id及子部门id
        List<Long> ids = new ArrayList<>();
        ids.addAll(departmentIds);
        for (Long departmentId : departmentIds) {
            //查询子部门id并添加到 集合中
            this.queryChildDepartmentIds(ids, departmentId);
        }

        //查询员工数量
        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.in(SysCompanyUser::getDepartmentId, ids);

        Integer count = companyUserMapper.selectCount(wrapper);

        return count == null ? 0 : count;
    }

    @Override
    public List<SysCompanyUserDTO> queryCompanyUser(Long companyId, Long userId) {
        //健壮性判断
        if(userId == null){
            return null;
        }

        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        if(companyId != null){
            wrapper.eq(SysCompanyUser::getCompanyId, companyId);
        }
        wrapper.eq(SysCompanyUser::getUserId, userId);
        wrapper.eq(SysCompanyUser::getEnable, 1);

        List<SysCompanyUser> companyUserList = companyUserMapper.selectList(wrapper);
        if(CollectionUtil.isNotEmpty(companyUserList)){
            List<SysCompanyUserDTO> companyUserDTOList = BeanHelper.copyWithCollection(companyUserList, SysCompanyUserDTO.class);
            //循环员工列表， 查询每个员工的角色信息
            for (SysCompanyUserDTO companyUserDTO : companyUserDTOList) {
                List<SysRole> roleList = roleMapper.selectRoleListByCompanyId(companyUserDTO.getId(), companyUserDTO.getCompanyId());
                if(CollectionUtil.isNotEmpty(roleList)){
                    companyUserDTO.setRoles(BeanHelper.copyWithCollection(roleList, SysRoleDTO.class));
                }
            }

            return companyUserDTOList;
        }
        return null;
    }

    @Override
    public SysCompanyUserDTO queryCompanyUserOne(Long userId) {
        if (userId!=null){
            SysCompanyUser sysCompanyUser = companyUserMapper.selectById(userId);
            return BeanHelper.copyProperties(sysCompanyUser,SysCompanyUserDTO.class);
        }
        return null;
    }

    @Override
    public PageResult<SysCompanyUserDTO> queryCompanyMemberListByPage(Long page,Long pageSize) {
        PageResult<SysCompanyUserDTO> pageResult = new PageResult<>();
        if (page == null) {
            //如果没有当前页 默认为1
            page = 1L;
        }
//分页查询参数
        Page<SysCompanyUser> companyUserPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
        companyUserPage = companyUserMapper.selectPage(companyUserPage, wrapper);
//获取每页显示的数据
        List<SysCompanyUser> sysCompanyUserList = companyUserPage.getRecords();
//如果有数据,就返回
        if (CollectionUtil.isNotEmpty(sysCompanyUserList)) {
            pageResult.setTotal(companyUserPage.getTotal());
            pageResult.setTotalPage(companyUserPage.getPages());
            pageResult.setRows(BeanHelper.copyWithCollection(sysCompanyUserList, SysCompanyUserDTO.class));
            return pageResult;
        }
        return new PageResult<>();


    }


    public void queryChildDepartmentIds(List<Long> ids , Long parentId ){
        //查询部门 的子部门列表
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.eq(SysDepartment::getParentId, parentId);
        List<SysDepartment> departmentList = departmentMapper.selectList(wrapper);
        if(CollectionUtil.isNotEmpty(departmentList)){
            //取出 部门列表中的id集合
            List<Long> departmentIds = departmentList.stream()
                    .map(department -> {
                        return department.getId();
                    }) //集合的映射
                    .collect(Collectors.toList());//指定要映射的类型
            //把id集合添加到 ids中
            ids.addAll(departmentIds);

            for (Long id : departmentIds) {
                // 查询 子部门的子部门id集合
                this.queryChildDepartmentIds(ids, id);
            }

        }
    }
}
